<?php
/**
 * PHP内置服务器路由文件
 * 处理URL重写，隐藏.php后缀
 * 使用方式: php -S localhost:8080 router.php
 */

$requestUri = $_SERVER['REQUEST_URI'];
$parsedUrl = parse_url($requestUri);
$path = $parsedUrl['path'];
$query = $parsedUrl['query'] ?? '';

// 静态文件处理
$staticExtensions = ['css', 'js', 'png', 'jpg', 'jpeg', 'gif', 'ico', 'svg', 'woff', 'woff2', 'ttf', 'eot'];
$pathInfo = pathinfo($path);

// 首先检查是否为静态文件请求
if (isset($pathInfo['extension']) && in_array(strtolower($pathInfo['extension']), $staticExtensions)) {
    $filePath = ltrim($path, '/');

    // 如果文件存在，直接提供
    if (file_exists($filePath)) {
        $extension = strtolower($pathInfo['extension']);
        $contentTypes = [
            'css' => 'text/css',
            'js' => 'application/javascript',
            'png' => 'image/png',
            'jpg' => 'image/jpeg',
            'jpeg' => 'image/jpeg',
            'gif' => 'image/gif',
            'ico' => 'image/x-icon',
            'svg' => 'image/svg+xml',
            'woff' => 'font/woff',
            'woff2' => 'font/woff2',
            'ttf' => 'font/ttf',
            'eot' => 'application/vnd.ms-fontobject'
        ];

        if (isset($contentTypes[$extension])) {
            header('Content-Type: ' . $contentTypes[$extension]);
        }

        // 添加缓存头
        header('Cache-Control: public, max-age=86400');
        header('Expires: ' . gmdate('D, d M Y H:i:s \G\M\T', time() + 86400));

        // 输出文件内容
        readfile($filePath);
        exit;
    }

    // 文件不存在，返回404
    http_response_code(404);
    echo 'File not found';
    exit;
}

// 安全检查 - 禁止访问敏感目录和文件
$blockedPaths = [
    '/config/', '/includes/', '/data/',
    '/.htaccess', '/.env', '/.git/'
];

foreach ($blockedPaths as $blocked) {
    if (strpos($path, $blocked) === 0) {
        http_response_code(404);
        echo "<!DOCTYPE html><html><head><title>404 Not Found</title></head><body><h1>404 Not Found</h1><p>The requested resource was not found.</p></body></html>";
        exit;
    }
}

// 禁止访问特定文件类型
if (preg_match('/\.(json|log)$/', $path)) {
    http_response_code(404);
    echo "<!DOCTYPE html><html><head><title>404 Not Found</title></head><body><h1>404 Not Found</h1><p>The requested resource was not found.</p></body></html>";
    exit;
}

// API路由处理
if (preg_match('/^\/api\/(.+)$/', $path, $matches)) {
    $apiEndpoint = $matches[1];
    $targetFile = "api/{$apiEndpoint}.php";

    if (file_exists($targetFile)) {
        // 设置环境变量，让API文件知道原始请求路径
        $_SERVER['ORIGINAL_REQUEST_URI'] = $requestUri;
        $_SERVER['SCRIPT_NAME'] = "/api/{$apiEndpoint}.php";

        // 保存当前目录，确保包含路径正确
        $originalDir = getcwd();
        chdir(__DIR__);

        require $targetFile;

        // 恢复原目录
        chdir($originalDir);
        exit;
    } else {
        http_response_code(404);
        header('Content-Type: application/json');
        echo json_encode(['error' => 'API endpoint not found'], JSON_UNESCAPED_UNICODE);
        exit;
    }
}

// Sitemap路由处理
if ($path === '/sitemap.xml') {
    $targetFile = 'api/sitemap.php';

    if (file_exists($targetFile)) {
        // 设置环境变量
        $_SERVER['ORIGINAL_REQUEST_URI'] = $requestUri;
        $_SERVER['SCRIPT_NAME'] = '/sitemap.xml';

        // 保存当前目录，确保包含路径正确
        $originalDir = getcwd();
        chdir(__DIR__);

        require $targetFile;

        // 恢复原目录
        chdir($originalDir);
        exit;
    }
}

// Robots.txt路由处理
if ($path === '/robots.txt') {
    $robotsFile = 'robots.txt';

    if (file_exists($robotsFile)) {
        header('Content-Type: text/plain; charset=utf-8');
        header('Cache-Control: public, max-age=86400'); // 缓存24小时
        readfile($robotsFile);
        exit;
    }
}

// 管理后台路由处理
if (preg_match('/^\/admin\/?(.*)$/', $path, $matches)) {
    $adminPath = $matches[1];
    
    // 处理 /admin 或 /admin/
    if (empty($adminPath) || $adminPath === '/') {
        $targetFile = 'admin/index.php';
    } else {
        // 移除末尾的斜杠
        $adminPath = rtrim($adminPath, '/');
        $targetFile = "admin/{$adminPath}.php";
    }
    
    if (file_exists($targetFile)) {
        // 设置环境变量
        $_SERVER['ORIGINAL_REQUEST_URI'] = $requestUri;
        $_SERVER['SCRIPT_NAME'] = "/{$targetFile}";
        
        // 保存当前目录，确保包含路径正确
        $originalDir = getcwd();
        chdir(__DIR__);
        
        require $targetFile;
        
        // 恢复原目录
        chdir($originalDir);
        exit;
    } else {
        http_response_code(404);
        echo "<!DOCTYPE html><html><head><title>404 Not Found</title></head><body><h1>404 Not Found</h1><p>Admin page not found.</p></body></html>";
        exit;
    }
}

// 处理其他无扩展名的请求
if (!pathinfo($path, PATHINFO_EXTENSION) && $path !== '/') {
    $phpFile = ltrim($path, '/') . '.php';
    
    if (file_exists($phpFile)) {
        // 设置环境变量
        $_SERVER['ORIGINAL_REQUEST_URI'] = $requestUri;
        $_SERVER['SCRIPT_NAME'] = "/{$phpFile}";
        
        // 保存当前目录，确保包含路径正确
        $originalDir = getcwd();
        chdir(__DIR__);
        
        require $phpFile;
        
        // 恢复原目录
        chdir($originalDir);
        exit;
    }
}

// 处理根路径
if ($path === '/') {
    if (file_exists('index.php')) {
        $_SERVER['ORIGINAL_REQUEST_URI'] = $requestUri;
        $_SERVER['SCRIPT_NAME'] = '/index.php';
        
        // 保存当前目录，确保包含路径正确
        $originalDir = getcwd();
        chdir(__DIR__);
        
        require 'index.php';
        
        // 恢复原目录
        chdir($originalDir);
        exit;
    }
}

// 检查是否访问了带.php后缀的文件，重定向到无后缀版本
if (preg_match('/^(.+)\.php$/', $path, $matches)) {
    $newPath = $matches[1];
    $redirectUrl = $newPath;
    if (!empty($query)) {
        $redirectUrl .= '?' . $query;
    }
    
    header("Location: $redirectUrl", true, 301);
    exit;
}

// 如果没有匹配的路由，返回404
http_response_code(404);
echo "<!DOCTYPE html><html><head><title>404 Not Found</title></head><body><h1>404 Not Found</h1><p>The requested resource was not found.</p></body></html>";
exit;
?> 